﻿using System;
using System.Data;
using System.ServiceModel;
using System.Windows.Forms;
using System.ComponentModel;
using Infragistics.Win.UltraWinGrid;

namespace DMSClient.Distributors
{
    public partial class Store : Form
    {
        private DataTable dt;
        private string ambient;
        WSHttpBinding Binding;
        EndpointAddress address;

        public Store()
        {
            InitializeComponent();

            this.ambient = Properties.Settings.Default.CurrentEnv;
            this.Text = this.ambient + " - Store Report";

            Binding = new WSHttpBinding();
            Binding.MaxReceivedMessageSize = Int32.MaxValue;
            Binding.MaxBufferPoolSize = Int32.MaxValue;
            Binding.CloseTimeout = TimeSpan.MaxValue;
            Binding.ReceiveTimeout = TimeSpan.MaxValue;
            Binding.SendTimeout = TimeSpan.MaxValue;
            Binding.Security.Mode = SecurityMode.None;
            Binding.ReaderQuotas.MaxStringContentLength = Int32.MaxValue;

            //address = new EndpointAddress("http://localhost:4872/DmsServices.svc");
            address = new EndpointAddress(Properties.Settings.Default.Server);
        }

        private void ugButton_Click(object sender, EventArgs e)
        {
            activarControles(false);
            bgwSearch.RunWorkerAsync();
        }

        private void Store_Load(object sender, EventArgs e)
        {
            uceDistributors.DisplayMember = "cdOrgUnit";
            uceDistributors.ValueMember = "idOrgUnit";

            DMSServices.DMSServicesClient client = new DMSClient.DMSServices.DMSServicesClient(Binding, address);
            string distributors = null;

            try
            {
                client.Open();
                distributors = client.getDistributorsList(ambient);
                client.Close();
            }
            catch (Exception ex)
            {
                this.BringToFront();
                MessageBox.Show(this, "Error trying to load Distributors List, you should check:\n\n" +
                                      "1. Your network connection.\n" +
                                      "2. Remote WCF Service is running.",
                    this.Text,
                    MessageBoxButtons.OK,
                    MessageBoxIcon.Error);
                this.BeginInvoke(new MethodInvoker(closeThis));
                return;
            }

            DataTable dt = new DataTable("dtDistributorsList");
            dt.Columns.Add("idOrgUnit");
            dt.Columns.Add("cdOrgUnit");

            DataSet ds = new DataSet();
            ds.Tables.Add(dt);

            System.IO.StringReader xmlSR = new System.IO.StringReader(distributors);
            ds.ReadXml(xmlSR, XmlReadMode.ReadSchema);
            uceDistributors.DataSource = dt;
            uceDistributors.SelectedIndex = 0;
            xmlSR.Close();
        }

        private void closeThis()
        {
            this.Close();
        }

        private void ugExport_Click(object sender, EventArgs e)
        {
            if (UGIntStore.Rows.Count < 1)
            {
                MessageBox.Show("There is no data to export", "Store Report", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                return;
            }
            System.Windows.Forms.SaveFileDialog dialogo = new System.Windows.Forms.SaveFileDialog();
            dialogo.DefaultExt = "xls";
            Infragistics.Win.UltraWinGrid.ExcelExport.UltraGridExcelExporter Exporter = new Infragistics.Win.UltraWinGrid.ExcelExport.UltraGridExcelExporter();
            if (dialogo.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                Exporter.Export(UGIntStore, dialogo.FileName);
                if (MessageBox.Show(this, "¿Desea abrir el archivo?", "Store Report", MessageBoxButtons.YesNo) == DialogResult.Yes)
                {
                    System.Diagnostics.Process.Start(dialogo.FileName);
                }
            }
        }

        private void bgwSearch_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
        {
            BackgroundWorker worker = sender as BackgroundWorker;
            DMSServices.DMSServicesClient client = new DMSClient.DMSServices.DMSServicesClient(Binding, address);
            string response = null;

            try
            {
                client.Open();
                response = client.StoreByDistributor(ambient, uceDistributors.Value.ToString());
                client.Close();
                if (worker.CancellationPending)
                {
                    e.Cancel = true;
                    return;
                }
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message, ex.InnerException);
            }

            dt = new DataTable("dtStore");
            dt.Columns.Add("cdStore", typeof(string));
            dt.Columns.Add("cdRegion", typeof(string));
            dt.Columns.Add("nmAddress", typeof(string));
            dt.Columns.Add("dsAddressComplement", typeof(string));
            dt.Columns.Add("nrZipCode", typeof(string));
            dt.Columns.Add("nmNeighborhood", typeof(string));
            dt.Columns.Add("cdClass1", typeof(string));
            dt.Columns.Add("cdClass2", typeof(string));
            dt.Columns.Add("cdCity", typeof(string));
            dt.Columns.Add("cdStatus", typeof(string));
            dt.Columns.Add("cdStoreBrand", typeof(string));
            dt.Columns.Add("dsName", typeof(string));
            dt.Columns.Add("dsCorporateName", typeof(string));

            DataSet dsStore = new DataSet();
            dsStore.Tables.Add(dt);
            System.IO.StringReader xmlSR = new System.IO.StringReader(response);
            dsStore.ReadXml(xmlSR, XmlReadMode.ReadSchema);
            xmlSR.Close();
        }

        private void bgwSearch_RunWorkerCompleted(object sender, System.ComponentModel.RunWorkerCompletedEventArgs e)
        {
            if (e.Error != null)
            {
                if (!this.IsDisposed)
                {
                    this.BringToFront();
                    MessageBox.Show(this, "Server response was not received, you should check:\n\n" +
                                          "1. Your network connection.\n" +
                                          "2. Remote WCF Service is running.",
                        this.Text,
                        MessageBoxButtons.OK,
                        MessageBoxIcon.Error);
                    activarControles(true);
                }
            }
            else if (!e.Cancelled && !this.IsDisposed)
            {
                UGIntStore.DataSource = dt;
                activarControles(true);
            }
            
        }

        private void activarControles(bool value)
        {
            loader.Visible = !value;
            UGIntStore.Enabled = value;
            ultraGroupBox1.Enabled = value;
        }

        private void Store_Resize(object sender, EventArgs e)
        {
            loader.Left = (this.Width - loader.Width) / 2;
            loader.Top = ((this.Height - loader.Height) / 2) - loader.Height;
        }

        private void Store_Shown(object sender, EventArgs e)
        {
            loader.Left = (this.Width - loader.Width) / 2;
            loader.Top = ((this.Height - loader.Height) / 2) - loader.Height;
        }

        private void Store_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (bgwSearch.IsBusy)
            {
                bgwSearch.CancelAsync();
            }
        }

        private void uceDistributors_ValueChanged(object sender, EventArgs e)
        {
            UGIntStore.DataSource = null;
        }

        private void UGIntStore_InitializeLayout(object sender, InitializeLayoutEventArgs e)
        {
            foreach (UltraGridBand bands in e.Layout.Bands)
            {
                foreach (UltraGridColumn ugc in bands.Columns)
                {
                    ugc.PerformAutoResize(PerformAutoSizeType.AllRowsInBand, true);
                }
            }
        }

       

        private void Store_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == (char)27)
            {
                this.Close();
            }
        }

        //private void ugButton_Click_1(object sender, EventArgs e)
        //{
        //    activarControles(false);
        //    bgwSearch.RunWorkerAsync();
        //}

        


    }
}